package cn.highedu.mvc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * 视图解析器
 * 单例模式
 */
public class ViewResolver {
    private static File root;
    private static File templatesDir;
    static {
        try{
            root = new File(
                    ViewResolver.class.getClassLoader().getResource(".").toURI()
            );
            templatesDir = new File(root, "templates");
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private static ViewResolver instance = new ViewResolver();

    private ViewResolver(){
    }

    public static ViewResolver getInstance() {
        return instance;
    }

    /**
     * 视图渲染方法
     * @param view 视图文件名，视图中有占位符合 ${name} ${gender}
     * @param model 显示在视图上的数据, {name=Tom, gender=male}
     * @return 渲染以后的网页html
     */
    public String render(String view, Map<String, Object> model) throws IOException {
        //找到模板文件
        File file = new File(templatesDir, view);
        //读取模板文件的全部内容
        InputStream in = new FileInputStream(file);
        byte[] bytes = new byte[(int)file.length()];
        in.read(bytes);
        String html = new String(bytes, StandardCharsets.UTF_8);
        System.out.println("读取了模板："+html);
        //对html模板中的占位符号进行替换
        for(Map.Entry<String, Object> entry: model.entrySet()){
            String name = entry.getKey();
            String value = entry.getValue() + "";
            //创建占位符的正则表达式
            String reg = "\\$\\{"+name+"\\}"; // $ { } 是正则特殊字符需要转义
            System.out.println("占位符的正则表达式 "+reg);
            //替换页面上的占位符
            html = html.replaceAll(reg, value);
        }
        System.out.println("替换结果:" + html);
        return html;
    }

    public static void main(String[] args) throws IOException {
        //视图
        String view = "view.html";
        //替换的数据
        Map<String, Object> model = new HashMap<>();
        model.put("name", "张亚峰");
        model.put("gender", "male");
        model.put("date", LocalDate.now().toString());
        //渲染视图
        ViewResolver viewResolver = ViewResolver.getInstance();
        String html = viewResolver.render(view, model);
        System.out.println(html);
    }
}












